package manager

import (
	"context"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

// DeviceInfo 设备信息结构体
type DeviceInfo struct {
	DeviceId      string
	SipServerId   string
	SipUri        string
	LastHeartbeat time.Time
}

// ClientManager 客户端管理器
type ClientManager struct {
	devices map[string]*DeviceInfo
	logger  logx.Logger
}

// NewClientManager 创建新的客户端管理器
func NewClientManager() *ClientManager {
	return &ClientManager{
		devices: make(map[string]*DeviceInfo),
		logger:  logx.WithCallerSkip(1),
	}
}

// Register 注册设备
func (m *ClientManager) Register(ctx context.Context, deviceId, sipServerId, sipUri string) (*DeviceInfo, error) {
	device := &DeviceInfo{
		DeviceId:      deviceId,
		SipServerId:   sipServerId,
		SipUri:        sipUri,
		LastHeartbeat: time.Now(),
	}
	m.devices[deviceId] = device
	m.logger.Infof("设备注册成功: %s", deviceId)
	return device, nil
}

// Unregister 注销设备
func (m *ClientManager) Unregister(ctx context.Context, deviceId string) error {
	delete(m.devices, deviceId)
	m.logger.Infof("设备注销成功: %s", deviceId)
	return nil
}

// GetDevice 获取设备信息
func (m *ClientManager) GetDevice(deviceId string) (*DeviceInfo, bool) {
	device, exists := m.devices[deviceId]
	return device, exists
}

// UpdateHeartbeat 更新设备心跳
func (m *ClientManager) UpdateHeartbeat(ctx context.Context, deviceId string) {
	if device, exists := m.devices[deviceId]; exists {
		device.LastHeartbeat = time.Now()
		m.logger.Debugf("设备心跳更新: %s", deviceId)
	}
}

// ListDevices 列出所有设备
func (m *ClientManager) ListDevices() []*DeviceInfo {
	devices := make([]*DeviceInfo, 0, len(m.devices))
	for _, device := range m.devices {
		devices = append(devices, device)
	}
	return devices
}

// IsOnline 检查设备是否在线
func (d *DeviceInfo) IsOnline() bool {
	return time.Since(d.LastHeartbeat) < 5*time.Minute
}